package com.mygenostics.listener;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.mygenostics.misc.WebUtil;
import com.mygenostics.persistence.UserBean;

import static com.mygenostics.constants.ApplicationConstants.*;
import static com.mygenostics.constants.SessionConstants.*;

public class AccessControlPhaseListener implements PhaseListener {

	private static final long serialVersionUID = 6710418030967326344L;
	
	private static Logger log = Logger.getLogger(AccessControlPhaseListener.class); 

	@Override
	public void afterPhase(PhaseEvent event) {
		FacesContext context = event.getFacesContext();	
		PhaseId phaseId = event.getPhaseId();
		
		if(phaseId == PhaseId.RESTORE_VIEW) {
			String requestUrl = ((HttpServletRequest)context.getExternalContext().getRequest())
				.getRequestURL().toString();
			
			
			if (requestUrl.contains(SECURED_PATH)) {
				UserBean user = (UserBean) WebUtil.getSessionMap().get(CURRENT_USER);
				NavigationHandler nh = context.getApplication().getNavigationHandler();
				
				if (user == null) {
					String targetView = WebUtil.normalizeViewId(context.getViewRoot().getViewId());
					if (log.isInfoEnabled()) {
						log.info("Security: redirect from " + targetView + " to login.");
					}
					WebUtil.getSessionMap().put(HISTRORY_PATH, targetView);
					nh.handleNavigation(context, null, LOGIN_VIEW);
				}
				else {
					String historyPath = (String)WebUtil.getSessionMap().get(HISTRORY_PATH);
					if (historyPath != null) {
						WebUtil.getSessionMap().put(HISTRORY_PATH, null);
						if (log.isInfoEnabled()) {
							log.info("Restore previous view: " + historyPath);
						}
						nh.handleNavigation(context, null, historyPath);

					}
				}
			}
		}

	}

	@Override
	public void beforePhase(PhaseEvent arg0) {
		// Do nothing

	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}
